﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreTransport.Business.Constants;
using StoreTransport.DAO;
using StoreTransport.Data;
using StoreTransport.Business.Helper;
using StoreTransport.Resources;

namespace StoreTransport.Presentation.Forms {
    public partial class UserListForm : Form {
        int id = 0;
        Dictionary<string, string> roleDic = null;
        public UserListForm() {
            InitializeComponent();
        }

        private void UserListForm_Load(object sender, EventArgs e) {
            _tbxLoginName.Select();
            _drpRoleList.DisplayMember = ColumnName.RoleName;
            _drpRoleList.ValueMember = ColumnName.ID;
            StoreTransportDataContext context = CommonHelper.GetContext();
            _drpRoleList.DataSource = context.Roles.OrderBy(c => c.RoleName);
            roleDic = context.Roles.ToDictionary(c => c.ID.ToString(), c => c.RoleName);
            LoadUserList();
        }

        private void LoadUserList() {
            _grdUsers.AutoGenerateColumns = false;
            var areaList = CommonHelper.GetContext().Users.
                Cast<User>().OrderBy(c => c.Username);
            List<PresentUserDTO> userList = new List<PresentUserDTO>();
            foreach (var r in areaList) {
                string role = string.Empty;
                if (r.Role != null && roleDic.ContainsKey(r.Role.ToString())) {
                    role = roleDic[r.Role.ToString()];
                }
                userList.Add(new PresentUserDTO(r.ID, r.Username, r.Password, r.Name, role));
            }
            _grdUsers.DataSource = userList.OrderBy(c => c.UserName).ToList();
        }

        private void _btxSave_Click(object sender, EventArgs e) {
            StoreTransportDataContext context = CommonHelper.GetContext();
            string errorMessage = CommonHelper.CheckRequiredField(_tbxLoginName.Text, _lblLogingName.Text);
            errorMessage += CommonHelper.CheckRequiredField(_tbxPassword.Text, _lblPassword.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage);
                return;
            }
            errorMessage += CommonHelper.CheckRequiredField(_tbxPassword.Text, _lblPassword.Text);
            if (!string.IsNullOrEmpty(errorMessage)) {
                MessageBox.Show(errorMessage);
                return;
            }
            User user = null;
            if (id == 0) {
                user = new User();
                if (context.Users.FirstOrDefault(c => c.Username.Equals(_tbxLoginName.Text)) != null) {
                    MessageBox.Show(string.Format(StoreTransportResource.Error_Dupplicate_User,
                        _tbxLoginName.Text));
                    return;
                }
                context.Users.InsertOnSubmit(user);
            } else {
                var item = context.Users.FirstOrDefault(c => c.Username.Equals(_tbxLoginName.Text));
                if (item != null && item.ID != id) {
                    MessageBox.Show(string.Format(StoreTransportResource.Error_Dupplicate_User,
                        _tbxLoginName.Text));
                    return;
                }
                user = context.Users.Where(c => c.ID.Equals(id)).First();
            }
            user.Username = _tbxLoginName.Text;
            user.Name = _tbxUserName.Text;
            user.Password = _tbxPassword.Text;
            user.Role = (int)_drpRoleList.SelectedValue;
            user.Description = _tbxDescription.Text;
            context.SubmitChanges();
            LoadUserList();
        }

        private void _btxCreate_Click(object sender, EventArgs e) {
            _tbxLoginName.Select();
            _tbxLoginName.Text = string.Empty;
            _tbxLoginName.ReadOnly = false;
            _tbxUserName.Text = string.Empty;
            _tbxPassword.Text = string.Empty;
            _tbxDescription.Text = string.Empty;
            id = 0;
            CommonHelper.ResetCombobox(_drpRoleList);
        }

        private void _btnDelete_Click(object sender, EventArgs e) {
            if (_grdUsers.SelectedRows.Count > 0) {
                DialogResult result = MessageBox.Show(StoreTransportResource.Message_ConfirmDelete,
                    StoreTransportResource.MessageBox_ConfirmDelete, MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.Yes) {
                    try {
                        StoreTransportDataContext context = CommonHelper.GetContext();
                        foreach (DataGridViewRow row in _grdUsers.SelectedRows) {
                            id = int.Parse(row.Cells[0].Value.ToString());
                            User selectedItem = context.Users.Where(c => c.ID.Equals(id)).First();
                            context.Users.DeleteOnSubmit(selectedItem);
                            context.SubmitChanges();
                        }
                        LoadUserList();
                        id = 0;
                    } catch (Exception ex) {
                        MessageBox.Show(StoreTransportResource.ErrorMessage_CanNotDeleteItem);
                    }
                }
            } else {
                MessageBox.Show(StoreTransportResource.NoItemSelected);
            }
        }

        private void _btxEdit_Click(object sender, EventArgs e) {
            if (_grdUsers.SelectedRows.Count > 0) {
                id = int.Parse(_grdUsers.SelectedRows[0].Cells[0].Value.ToString());
                EditItem();
            }
        }

        private void EditItem() {
            User selectedItem = CommonHelper.GetContext().Users.Where(c => c.ID.Equals(id)).First();
            _tbxLoginName.Text = selectedItem.Username;
            _tbxLoginName.ReadOnly = true;
            _tbxUserName.Text = selectedItem.Name;
            _tbxPassword.Text = selectedItem.Password;
            _tbxDescription.Text = selectedItem.Description;
            if (selectedItem.Role != null) {
                _drpRoleList.SelectedValue = selectedItem.Role;
            } else {
                CommonHelper.ResetCombobox(_drpRoleList);
            }
        }

        private void _grdUsers_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
            id = int.Parse(_grdUsers.Rows[e.RowIndex].Cells[0].Value.ToString());
            EditItem();
        }
    }
}
